<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2023 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: guanzheng
// +----------------------------------------------------------------------

// 应用公共文件

/**
 * curl函数封装
 * @param  $method        请求方式GET、POST
 * @param  $url           请求接口地址
 * @param  $data          提交数据 　
 * @return array
 */
function httpGet($url, $method = 'get', $data = '', $headers = array("Content-type:application/json","Accept:application/json"))
{
    $ch = curl_init();//初始化
    //设置URL和相应的选项
    curl_setopt($ch, CURLOPT_URL, $url);//指定请求的URL
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));//提交方式
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//不验证SSL
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);//不验证SSL
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);//设置HTTP头字段的数组
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible;MSIE 5.01;Windows NT 5.0)');//头的字符串
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);//自动设置header中的Referer:信息
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//提交数值
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//是否输出到屏幕上,不直接输出
    $temp = curl_exec($ch);//执行并获取结果
    curl_close($ch);
    return $temp;//return 返回值
}

/**
 * API返回函数
 * @param  int     $messageCode    状态码
 * @param  string  $message        消息
 * @param  array   $data           数据
 * @return json
 */
function apiReturn($messageCode, $message, $data = '')
{
    $return_data = array(
        'messageCode'=>$messageCode,
        'message'=>$message,
        'data'=>$data
    );
    echo json_encode($return_data);exit;
}

/**
 * 下载文件到本地
 * @param  string    $url             图片路径
 * @param  string    $absolute_path   下载路径
 */
function download($url, $absolute_path = '')
{
    $content = file_get_contents($url);
    file_put_contents($absolute_path, $content);
}

/**
 * 函数：提示信息
 * @param $message 提示信息
 * @param $url     跳转地址,默认跳转到上一页
 */
function message($message, $url = '')
{
	echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
    echo '<script>alert("'.$message.'");</script>';
    if (empty($url)) {
        echo '<script>window.history.back();</script>';
    }else{
        echo '<script>window.location.href="/admin.php/'.$url.'";</script>';
    }
    exit();
}

/**
 * 函数：加密
 * @param string            密码
 * @return string           加密后的密码
 */
function password($password)
{
    for ($i=0; $i < 3; $i++) {
        $password = sha1(strrev($password));
    }
    return $password;
}

// 获取客户端mac地址
function clientMac()
{
    // $string=exec('getmac');
    // $mac=substr($string, 0, 17); 

    // return $mac;
    return '';
}

// 获取ip归属地
function ipArea($ip)
{
    include "../vendor/topthink/IpLocation.php";//引入文件
    $Ips =new \IpLocation\IpLocation('UTFWry.dat'); // 实例化类 参数表示IP地址库文件
    $area = $Ips->getlocation($ip); // 获取某个IP地址所在的位置
    return $area;
}

/*
 将无限极分类，重新排序：
    子分类跟随父分类
    有级别字段

 $typeList：原始的分类集合
 $p_id：某分类id
 $level：级别
*/
function goodsTypeReset($typeList,$p_id,$level=0,$idN='id',$pageN='pid'){
    $level++; //累加级别
    $data=array();
    foreach($typeList as $val){
        //若某元素的 父id等于要求的$p_id
        if($val[$pageN] == $p_id){ 
            // 0. 为分类，增加字段
            $val['level'] = $level;

            // 1. 满足条件的分类，存储进 $data;
            $data[] = $val;

            //2. 查询 满足条件分类的子分类
            $sonType = goodsTypeReset($typeList,$val[$idN],$level);

            //3. 合并，当前分类的子分类
            $data = array_merge($data,$sonType);
        }
    }
    return $data;
}
/*
 * 文件上传
 * */
function upload(){
    $file = request()->file('file');
    if($file){
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        if($info){
            return $info->getSaveName();
        }else{
            apiReturn(401,$file->getError());
        }
    }
}
use think\Cache;
use app\index\model\CrmFenzu;
/*
 * input
 * 全局的固定变量，不要动
 * */
function accept($zu_id,$is_xiaoshou,$username){
    $query = input();
    foreach ($query as $key=>$value){
        if ($value === ''){
            unset($query[$key]);
        }
    }
    $query['rows'] = isset($query['rows'])?$query['rows']:10;
    $query['page'] = isset($query['page'])?$query['page']:1;
    $CrmFenzu = new CrmFenzu();
    $username_arr = $CrmFenzu->authority($zu_id,$is_xiaoshou,$username);
    if(is_array($username_arr)){
        if(isset($query['manage_id'])){//前端点击查询
            if(count($username_arr)>1){
                if(!in_array($query['manage_id'],$username_arr))apiReturn(400,'您没有权限查看此订单');
            }elseif (count($username_arr)==1){
                if($username_arr[0]!=$query['manage_id'])apiReturn(400,'您没有权限查看此订单');
            }
            $query['manage_id'] = [$query['manage_id']];
        }else{
            $query['manage_id'] =$username_arr;
        }
    }else{
        if(isset($query['manage_id']))$query['manage_id'] = [$query['manage_id']];
    }
    //$username_arr = unserialize(Cache::get('zu_username'.$username));
    return $query;
}

/*
 * 自定义日志
 * */
 function express($mark, $log_content, $keyp = "") {
    $max_size = 30000000;
    if ($keyp == "") {
        $log_filename = RUNTIME_PATH . '/' . date('Ym-d') . ".log";
    } else {
        $log_filename = RUNTIME_PATH . '/' . $keyp . ".log";
    }

    if (file_exists($log_filename) && (abs(filesize($log_filename)) > $max_size)) {
        rename($log_filename, dirname($log_filename) . DS . date('Ym-d-His') . $keyp . ".log");
    }

    $t = microtime(true);
    $micro = sprintf("%06d", ($t - floor($t)) * 1000000);
    $d = new \DateTime (date('Y-m-d H:i:s.' . $micro, $t));
    if(is_array($log_content)){
        $log_content = JSONReturn($log_content);
    }

    file_put_contents($log_filename, '   ' . $d->format('Y-m-d H:i:s u') . " key：" . $mark . "\r\n" . $log_content . "\r\n------------------------ --------------------------\r\n", FILE_APPEND);
}

function JSONReturn($result)
{
    return json_encode($result,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
}

 function ipIndex($ip)
{
    // $ip = "222.22.22.11";// 默认设置一个ip地址(可自行获取)
    include "../vendor/topthink/IpLocation.php";//引入文件
    $Ips =new \IpLocation\IpLocation('UTFWry.dat'); // 实例化类 参数表示IP地址库文件
    $area = $Ips->getlocation($ip); // 获取某个IP地址所在的位置
    return $area;
}

/*
将无限极分类，重新排序：
    子分类跟随父分类
    有级别字段

$typeList：原始的分类集合
$p_id：某分类id
$level：级别
*/
function myTypeReset_2($typeList,$p_id,$level=0,$idN='menu_id',$pageN='pid'){
    $level++; //累加级别
    $data=array();
    foreach($typeList as $val){
        if($val[$pageN]==$p_id){ //若某元素的 父id==要求的$p_id
            // 0. 为分类，增加字段
            $val['level']=$level;

            // 1. 满足条件的分类，存储进 $data;
            $data[]=$val; 

            //2. 查询 满足条件分类的子分类
            $sonType=myTypeReset_2($typeList,$val[$idN],$level);

            //3. 合并，当前分类的子分类
            $data=array_merge($data,$sonType);
        }
    }
    return $data;
}
function myTypeReset_3($typeList,$p_id,$level=0,$idN='menu_id',$pageN='pid'){
    $level++; //累加级别
    $data=array();
    foreach($typeList as $val){
        if($val[$pageN]==$p_id){ //若某元素的 父id==要求的$p_id
            // 0. 为分类，增加字段
            $val['level']=$level;

            // 1. 满足条件的分类，存储进 $data;
            $data[]=$val;

            //2. 查询 满足条件分类的子分类
            $sonType=myTypeReset_2($typeList,$val[$idN],$level);

            //3. 合并，当前分类的子分类
            $data=array_merge($data,$sonType);
        }
    }
    return $data;
}

use oss\Oss;
function uploadOss($file){
//    $file = request()->file('file');
    if (empty($file)) {
        apiReturn(SER_ERR,'文件不能为空');
    }
    $path = ROOT_PATH . 'public' . DS . 'uploads'.DS.'img'.DS;
    $file_name = md5(time().rand(10000000,9999999));
    $info = $file->move($path,$file_name);
    if($info){
        $file_name = $file_name.'.'.$info->getExtension();
        $oss_server = new Oss();
        $upload = $oss_server->updateOss($path.$file_name,$file_name);
        if(is_string($upload)){
            apiReturn(SER_NOT,$upload);
        }
        try{
            if(file_exists($path.$file_name)){
                unlink($path.$file_name);
            }
        } catch(Exception $exception){
            return  $upload['info']['url'];
           // apiReturn(SER_ERR,$exception->getMessage());
        }
        return  $upload['info']['url'];
    }else{
        apiReturn(SER_NOT,$file->getError());
    }
}

function deleteOss($url){
    $oss_server = new Oss();
    $delete = $oss_server->deleteOss($url);
    if(is_string($delete)){
        apiReturn(SER_NOT,$delete);
    }
    apiReturn(SER_SUCCESS,'已删除');
}

function  changeTimeType($seconds)
{
    if ($seconds > 3600) {
        $hours = intval($seconds / 3600);
        $time = $hours . ":" . gmstrftime('%M:%S', $seconds);
    } else {
        $time = gmstrftime('%H:%M:%S', $seconds);
    }
    return $time;
}

?>
